﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Nirvana
{
    [RequireComponent(typeof(RawImage))]
    [ExecuteInEditMode]
    public class UIRawImageLoadSync : MonoBehaviour
    {
        [SerializeField]
        [Tooltip("The raw image asset.")]
        private TextAsset asset;
        private Texture texture;
        private RawImage rawImage;

        void Awake()
        {
            this.Load();
        }

#if UNITY_EDITOR
        void OnValidate()
        {
            this.Clear();
            this.Load();
        }
#endif

        void OnDestroy()
        {
            this.Clear();
        }



        private void Load()
        {
            if (this.rawImage == null) this.rawImage = GetComponent<RawImage>();
            if(asset != null)
            {
                this.texture = this.LoadTexture(this.asset);
                this.texture.hideFlags = HideFlags.DontSave;
                this.rawImage.texture = this.texture;
            }
        }

        private Texture2D LoadTexture(TextAsset textAsset)
        {
            byte[] bytes = textAsset.bytes;
            var format = TextureFormat.RGBA32;
            if(bytes != null && bytes[1] == 80 && bytes[2]==78 && bytes[3] == 71)
            {
                format = TextureFormat.RGBA32;
            }

            var texture2D = new Texture2D(2, 2, format,false);
            if (!ImageConversion.LoadImage(texture2D, bytes,true))
            {
                return null;
            }
            texture2D.wrapMode = TextureWrapMode.Clamp;
            return texture2D;
        }

        private void Clear()
        {
            if (this.texture != null)
            {
                if (Application.isPlaying)
                {
                    UnityEngine.Object.Destroy(this.texture);
                }
                else
                {
                    UnityEngine.Object.DestroyImmediate(this.texture);
                }
                this.texture = null;
            }
        }


    }
}

